package com.fary.config;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.AnnotationMap;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Configuration
public class JacksonConfig implements Jackson2ObjectMapperBuilderCustomizer {

    @Override
    public void customize(Jackson2ObjectMapperBuilder builder) {
        builder.serializerByType(Date.class, new CustomizeDateSerializer());
        builder.deserializerByType(Date.class, new CustomizeDateDeserializer());
        builder.deserializerByType(String.class, new CustomizeStringDeserializer());
    }

    @Bean
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        SerializerFactory serializerFactory = objectMapper.getSerializerFactory().withSerializerModifier(new CustomizeBeanSerializerModifier());
        objectMapper.setSerializerFactory(serializerFactory);
        return objectMapper;
    }

    public static class CustomizeDateSerializer extends JsonSerializer<Date> implements ContextualSerializer {

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            String formatTime = DateUtil.formatTime(value);
            if ("00:00:00".equals(formatTime)) {
                gen.writeString(DateUtil.formatDate(value));
            } else {
                gen.writeString(DateUtil.formatDateTime(value));
            }
        }

        @Override
        public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
            AnnotationMap annotated = property.getMember().getAllAnnotations();

            JsonFormat jsonFormat = annotated.get(JsonFormat.class);
            if (jsonFormat != null && StrUtil.isNotBlank(jsonFormat.pattern())){
                return new PatternDateSerializer(jsonFormat.pattern());
            }
            return this;
        }
    }

    public static class PatternDateSerializer extends JsonSerializer<Date> {

        private String pattern = "";

        public PatternDateSerializer(String pattern) {
            this.pattern = pattern;
        }

        @Override
        public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            gen.writeString(DateUtil.format(value, pattern));
        }
    }

    public static class CustomizeDateDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            try {
                if (StrUtil.isBlank(jsonParser.getValueAsString())) {
                    return null;
                }
                return DateUtil.parse(jsonParser.getValueAsString(), "yyyy", "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "HH:mm:ss");
            } catch (Exception e) {
                return DateUtil.date(jsonParser.getValueAsLong());
            }
        }
    }

    public static class CustomizeStringDeserializer extends JsonDeserializer<String> {
        @Override
        public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            return StrUtil.trimEnd(jsonParser.getValueAsString());
        }
    }


    /**
     * 转json字符串时，Null换成 ""、[]、0、false
     */
    public static class CustomizeBeanSerializerModifier extends BeanSerializerModifier {
        @Override
        public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
            //循环所有的beanPropertyWriter
            for (BeanPropertyWriter beanProperty : beanProperties) {
                JsonInclude classAnnotation = beanProperty.getMember().getDeclaringClass().getAnnotation(JsonInclude.class);
                JsonInclude annotation = beanProperty.getAnnotation(JsonInclude.class);
                if (classAnnotation != null || annotation != null) {
                    continue;
                }
                //判断字段的类型，如果是array，list，set则注册nullSerializer
                if (isArrayType(beanProperty)) {
                    //给writer注册一个自己的nullSerializer
                    beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
                            if (value == null) {
                                jsonGenerator.writeStartArray();
                                jsonGenerator.writeEndArray();
                            }
                        }
                    });
                } else if (isNumberType(beanProperty)) {
                    beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
                            jsonGenerator.writeNumber(0);
                        }
                    });
                } else if (isBooleanType(beanProperty)) {
                    beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
                            jsonGenerator.writeBoolean(false);
                        }
                    });
                } else if (isStringType(beanProperty) || isDateType(beanProperty)) {
                    beanProperty.assignNullSerializer(new JsonSerializer<Object>() {
                        @Override
                        public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider serializers) throws IOException {
                            jsonGenerator.writeString(StrUtil.EMPTY);
                        }
                    });
                }
            }
            return beanProperties;
        }

        /**
         * 是否是数组
         */
        private boolean isArrayType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
        }

        /**
         * 是否是int
         */
        private boolean isNumberType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return Number.class.isAssignableFrom(clazz);
        }

        /**
         * 是否是boolean
         */
        private boolean isBooleanType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.equals(Boolean.class);
        }

        /**
         * 是否是string
         */
        private boolean isStringType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
        }

        /**
         * 是否是日期
         */
        private boolean isDateType(BeanPropertyWriter writer) {
            Class<?> clazz = writer.getType().getRawClass();
            return clazz.equals(Date.class);
        }

    }

}
